﻿using AdminSystem.Applications;
using AdminSystem.Domain.User;
using AdminSystem.Repositories;
using AdminSystem.Write.API.Command.TracebilityCommand;
using AdminSystem.Write.API.DTOS;
using MediatR;

namespace AdminSystem.Write.API.Handers.TracebilityHander
{
    public class TracebilityQueryCommandHandler : IRequestHandler<TracebilityQueryCommand, ApiResult<ApiPaging<TracebilityDTO>>>
    {
        private readonly IRepository<Tracebility> repository;
        private readonly IRepository<Shopp> shoppRepository;

        public TracebilityQueryCommandHandler(IRepository<Tracebility> repository, IRepository<Shopp> ShoppRepository)
        {
            this.repository = repository;
            shoppRepository = ShoppRepository;
        }
        /// <summary>
        /// 查询方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>00
        /// <returns></returns>
        public async Task<ApiResult<ApiPaging<TracebilityDTO>>> Handle(TracebilityQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<ApiPaging<TracebilityDTO>> result = new ApiResult<ApiPaging<TracebilityDTO>>();
                result.statusCode = StatusCode.Success;
                result.Message = "查询成功";
                var tracebilities = await repository.GetAll();
                var shopps = await shoppRepository.GetAll();
                var list = from a in tracebilities
                           join b in shopps on a.ShoppId equals b.ShoppId
                           where a.IsDelete == false
                           select new TracebilityDTO
                           {
                               Id = a.Id,
                               TraceabilityId = a.TraceabilityId,
                               ShoppId = a.ShoppId,
                               ShoppName = b.ShoppName,
                               ProBatch = a.ProBatch,
                               ShelfLife = a.ShelfLife,
                               ProLicense = a.ProLicense,
                               Manufacturers = a.Manufacturers,
                               CoverPic = a.CoverPic,
                               IsDelete = a.IsDelete
                           };
                var totalCount = list.Count();
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Size);
                list = list.OrderBy(x => x.Id).Skip((request.Index - 1) * request.Size).Take(request.Size);
                ApiPaging<TracebilityDTO> apiPaging = new ApiPaging<TracebilityDTO>();
                apiPaging.TotalPage = totalPage;
                apiPaging.TotalCount = totalCount;
                apiPaging.Data = list.ToList();
                result.Data = apiPaging;
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
